package com.demo.draw;

import com.demo.model.Card;
import com.demo.view.CardsView;

/**
 * 绘画新卡片出现的缩放动画
 */
public class DrawNewCard implements Runnable {
    private final Card card;
    private int d = 20;

    public DrawNewCard(Card card) {
        this.card = card;
    }

    public DrawNewCard(Card card, int d) {
        this(card);
        this.d = d;
    }

    /**
     * 根据向量值进行缩放
     *
     * @param ox 原点x坐标
     * @param oy 原点y坐标
     * @param d  向量的模
     */
    private void scale(int ox, int oy, int d) {
        // 由于图形为正方形，作用在顶点的向量在水平和垂直的分量是等大的，成45°角
        card.setX(ox - d);
        card.setY(oy - d);
        card.setWidth(d * 2);
        card.setHeight(d * 2);
    }

    @SuppressWarnings("BusyWait")
    @Override
    public void run() {
        CardsView cardsView = CardsView.getInstance();
        int endX = CardsView.transColumnToX(card.getColumn());
        int endY = CardsView.transRowToY(card.getRow());
        int ox = endX + CardsView.edge / 2;
        int oy = endY + CardsView.edge / 2;
        try {
            do {
                scale(ox, oy, d);
                d += 1;
                cardsView.repaint();
                Thread.sleep(5);
            } while (card.getX() > endX - 5 && card.getY() > endY - 5);
            // 缩小
            do {
                scale(ox, oy, d);
                d -= 1;
                cardsView.repaint();
                Thread.sleep(10);
            } while (card.getX() < endX && card.getY() < endY);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        // TODO 这里可能添加一些代码，当前卡片缩放动画到最后并没有设置其标准大小，当前参数下的卡片大小为2的倍数，scale计算正好没有误差
        card.newCard = false;
    }
}
